<template>
  <div class="map-container" ref="mapContainer"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";

const mapContainer = ref(null);
const mapInstance = ref(null);

// 初始化地图
const initMap = async () => {
  try {
    window._AMapSecurityConfig = {
      securityJsCode: import.meta.env.VITE_AMAP_JSCODE,
    };

    const AMap = await AMapLoader.load({
      key: import.meta.env.VITE_AMAP_KEY,
      version: "2.0",
      plugins: ["AMap.DistrictSearch"],
    });

    mapInstance.value = new AMap.Map(mapContainer.value, {
      viewMode: "2D",
      zoom: 5,
      center: [104.195, 35.861],
    });

    // 加载省级行政区划层
    const districtLayer = new AMap.DistrictLayer.Province({
      zIndex: 10,
      SOC: "CHN", // 中国
      depth: 4,
      styles: {
        "nation-stroke": "#22FFFF",
        "province-stroke": "#666",
        fill: "rgba(200,200,200,0.15)", // 省级填充透明度调低
        "province-stroke-width": 1,
      },
    });

    districtLayer.setMap(mapInstance.value);

    // 绑定点击事件
    districtLayer.on("click", (event) => handleProvinceClick(event, AMap));

  } catch (error) {
    console.error("地图初始化失败:", error);
  }
};

// 处理省份点击
const _handleProvinceClick = async (event, AMap) => {
  console.log("省份点击事件:", event);
  const provinceName = event.props.NAME_CHN;


  // 通过行政区名称查询边界细节
  const district = new AMap.DistrictSearch({
    level: "province",
    extensions: "all",
    showbiz: false,
  });

  // 异步查询
  const result = await new Promise((resolve, reject) => {
    district.search(event.props.NAME_CHN, (status, result) => {
      if (status === "complete") resolve(result);
      else reject(result);
    });
  });
  // 获取该省份的边界坐标集合
  const boundaries = result.districtList[0].boundaries;
  console.log("获取该省份的边界坐标集合", boundaries);

  boundaries.forEach((boundary) => {
    // 创建高亮覆盖层
    const polygon = new AMap.Polygon({
      path: boundary,
      fillColor: "#FF6B6B",
      strokeColor: "#FF6B6B",
      strokeWeight: 2,
      strokeOpacity: 1,
      extData: { provinceName },
    });
    polygon.on("mouseover", () => {
      polygon.setOptions({
        fillOpacity: 0.7,
        fillColor: "#7bccc4",
      });
    });
    polygon.on("mouseout", () => {
      polygon.setOptions({
        fillOpacity: 0.5,
        fillColor: "#FF6B6B",
      });
    });
    polygon.on("click", (e) => {
      console.log("点击了高亮覆盖物", polygon.getExtData());
    });
    mapInstance.value.add(polygon);
  });
};

const debounce = (fn, delay = 300) => {
  let timer = null
  return (...args) => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => fn.apply(this, args), delay)
  }
}
// 绑定防抖处理
const handleProvinceClick = debounce(_handleProvinceClick, 300)

onMounted(initMap);
onUnmounted(() => {
  if (mapInstance.value) mapInstance.value.destroy();
});


</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100vh;
  min-height: 600px;
  border: 1px solid #eee;
  border-radius: 8px;
}
</style>
